<template>
  <!-- 模态框 -->
  <div class="modal">
    <!-- 遮罩层 与登录框同级 避免事件冒泡 -->
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <!-- 登录框 -->
    <div class="loginBox">
      <div class="close" @click="changeIsShowLoginModal(false)"></div>

      <!-- 导航区域 -->
      <section class="nav">
        <a href="#" @click="isShowPhone = true" :class="{ active: isShowPhone }"
          >手机号登录</a
        >
        <span> | </span>
        <a href="#" @click="showQR" :class="{ active: !isShowPhone }"
          >微信扫码登录</a
        >
      </section>
      <!-- 内容区域 -->
      <div class="content">
        <!-- 手机号登录内容 -->
        <div class="phoneLogin" v-show="isShowPhone">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              class="ipt"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="arr"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机验证码"
              class="ipt"
              v-model="code"
            />
            <!-- <button class="btncode" @click="getCode">
              {{ isShowCount ? count + "s" : "获取验证码" }}
            </button> -->
            <!-- 避免重复调用定时器 -->
            <button class="btncode" @click="getCode" v-show="!isShowCount">
              获取验证码
            </button>
            <button class="btncode" v-show="isShowCount">{{ count }} s</button>
          </div>
          <div class="row">
            <button class="btnlogin" @click="submitFn">登录</button>
          </div>
        </div>
        <div class="qrLogin" v-show="!isShowPhone" id="weixin">
          微信扫码登录内容
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions } from "vuex";
import { sendSMSAPI, phoneReginAPI, bindingAPI } from "@/request/api";
import { validatePhoneNumber } from "@/utils";
export default {
  data() {
    return {
      isShowPhone: true,
      msg: "向右滑动",
      arr: [
        require("../assets/img/integral-01.9386d4bf.png"),
        require("../assets/img/integral-02.150d92a1.png"),
      ],
      phoneNumber: "",
      count: 5,
      isShowCount: false,
      code: "",
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showModal/changeIsShowLoginModal",
      changeIsLogin: "loginStatus/changeIsLogin",
      changeIsShowToast: "showToast/changeIsShowToast",
    }),
    ...mapActions({
      asyncChangeIsShowToast: "showToast/asyncChangeIsShowToast",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    // 倒计时拆分
    timerFn() {
      // console.log(1);
      this.isShowCount = true;
      let timer = setInterval(() => {
        this.count--;
        if (this.count <= 0) {
          this.count = 5;
          clearInterval(timer);
          this.isShowCount = false;
        }
      }, 1000);
    },
    // 提取手机号码验证和滑块验证
    toVerify() {
      // 1.判断手机号是否正确,不正确提示
      if (!validatePhoneNumber(this.phoneNumber)) {
        // return alert("请输入正确的手机号码");
        // this.changeIsShowToast({
        //   isShow: true,
        //   msg: "手机号码",
        //   type: "danger",
        // });

        this.asyncChangeIsShowToast({
          isShow: true,
          msg: "手机号码",
          type: "danger",
        });
        return;
      }
      // 2.滑块验证码不正确 提示
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        this.asyncChangeIsShowToast({
          isShow: true,
          msg: "请滑动滑块完成验证!",
          type: "danger",
        });
        return; //alert("请滑动滑块完成验证!");
      }
      // 没有设置return函数默认返回undefined
      return true;
    },
    // 获取微信二维码
    showQR() {
      this.isShowPhone = false;
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9",
      });
    },
    // 获取验证码
    async getCode() {
      // 手机号码验证和滑块验证
      let flag = this.toVerify();
      // 函数封装里面的return调用函数仍然执行下面的内容
      if (!flag) return;

      // 发请求
      let res = await sendSMSAPI({ phone: this.phoneNumber });
      console.log("发送手机验证码" + res);
      if (!res) return;
      alert("发送成功");
      // 获取验证码--60s倒计时功能
      // 计时器
      this.timerFn();
      console.log(res);

      console.log("end.....");
    },
    // 登录按钮
    async submitFn() {
      // 以msg文字内容来判断是否有进行拼图滑块验证
      // 1.验证手机
      // 2.验证滑块
      if (!this.toVerify()) return;
      // 3.验证验证码不为空
      if (!this.code.trim()) {
        this.asyncChangeIsShowToast({
          isShow: true,
          msg: "请滑动滑块完成验证!",
          type: "danger",
        });
        return; //alert("请输入正确的验证码")
      }
      // 4.发送登录请求
      // 手机号验证码登录
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        res = await bindingAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
          uuid,
        });
      } else {
        res = await phoneReginAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
        });
      }

      if (!res) return;
      // 1.登陆成功提示
      alert("登录成功!");
      console.log("登陆成功", res);
      // 2.存储token      obj.a=obj[a]
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      // 3.关闭模态框
      this.changeIsShowLoginModal(false);
      // 4.改变登录按钮状态(SPA不建议使用刷新,利用状态切换控制)
      this.changeIsLogin(true);

      // 绑定1清除code
      uuid && this.$router.push(this.$route.path);
      // 绑定2删除uuid
      localStorage.removeItem("uuid");

      // 登陆成功获取用户信息渲染
      this.asyncChangeUserInfo();
    },
  },
};
</script>

<style lang="less" scoped>
.modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .loginBox {
    position: absolute;
    inset: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    .close {
      width: 22px;
      height: 22px;
      background: url("../assets/img/close.png");
      position: absolute;
      right: 60px;
      top: 20px;
      cursor: pointer;
    }
    .nav {
      text-align: center;
      margin-top: 30px;
      a,
      span {
        text-decoration: none;
        color: #ccc;
      }
      a {
        &.active {
          color: #333;
          font-weight: bold;
        }
      }
    }
    .content {
      width: 355px;
      height: 300px;

      margin: 20px auto;
      .phoneLogin {
        .row {
          display: flex;
          margin-bottom: 20px;
        }

        .ipt {
          flex: 1;
          height: 50px;

          text-indent: 1em;
        }
        .btncode {
          height: 54px;
          width: 85px;
          margin-left: 20px;
          outline: none;
          border: none;
          background-color: #06348e;
          color: #fff;
        }
        .btnlogin {
          height: 50px;
          width: 100%;
          background-color: #06348e;
          color: #fff;
          border: none;
        }
        button {
          cursor: pointer;
        }
      }
      .qrLogin {
        text-align: center;
      }
    }
  }
}

// 对子组件操作加上/deep/
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>